<template>
	<view class="test-page">
		<view class="page-header">
			<text class="page-title">玩家资料管理</text>
			<text class="page-desc">管理您的头像、昵称等个人信息</text>
		</view>

		<view class="storage-info-card">
			<view class="card-header">
				<text class="card-title">存储信息概览</text>
				<view class="card-actions">
					<button class="btn-refresh" @click="loadStorageData">
						<uni-icons type="refresh" size="18"></uni-icons>
						刷新数据
					</button>
					<button class="btn-clear" @click="clearStorageData">
						<uni-icons type="trash" size="18"></uni-icons>
						清除数据
					</button>
				</view>
			</view>

			<view class="storage-stats">
				<view class="stat-item">
					<text class="stat-label">最后更新时间：</text>
					<text class="stat-value">{{ lastUpdateTime || '从未更新' }}</text>
				</view>
				<view class="stat-item">
					<text class="stat-label">存储键数量：</text>
					<text class="stat-value">{{ Object.keys(storageData).length }}</text>
				</view>
			</view>
		</view>

		<view class="data-section">
			<text class="section-title">玩家资料编辑</text>

			<view class="data-card" v-if="hasUserData">
				<!-- 头像显示区域 -->
				<view class="avatar-container">
					<view class="avatar-wrapper">
						<image 
							class="user-avatar" 
							:src="getAvatarUrl()" 
							mode="widthFix"
							@click="chooseAvatar"
						></image>
						<view class="avatar-upload-overlay" @click="chooseAvatar">
							<uni-icons type="camera" size="30" color="#fff"></uni-icons>
						</view>
					</view>
					<text class="avatar-hint">点击更换头像</text>
				</view>
				
				<!-- 昵称编辑区域 -->
				<view class="nickname-edit">
					<text class="data-key">昵称：</text>
					<view class="nickname-input-group">
						<input 
							class="nickname-input" 
							v-model="newNickname" 
							placeholder="请输入新昵称"
							:placeholder-style="{color: '#ccc'}"
						/>
						<button class="btn-save-nickname" @click="updateNickname">
							保存
						</button>
					</view>
				</view>
				
				<view class="data-item">
					<text class="data-key">当前昵称：</text>
					<text class="data-value">{{ userData.nickname || '未设置' }}</text>
				</view>
				
				<view class="data-item">
					<text class="data-key">用户名：</text>
					<text class="data-value">{{ userData.username || '未设置' }}</text>
				</view>
				
				<view class="data-item">
					<text class="data-key">角色：</text>
					<text class="data-value">{{ userData.role || '未设置' }}</text>
				</view>
				
				<view class="data-item">
					<text class="data-key">头像URL：</text>
					<text class="data-value url-value">{{ userData.avatarUrl || '使用默认头像' }}</text>
				</view>
				
				<view class="data-item">
					<text class="data-key">OpenID：</text>
					<text class="data-value">{{ userData.openid || '未获取' }}</text>
				</view>
				
				<view class="data-item">
					<text class="data-key">Token：</text>
					<text class="data-value token-value">{{ userData.token ? '已存在（部分隐藏）' : '未设置' }}</text>
					<text class="token-preview" v-if="userData.token">{{ maskToken(userData.token) }}</text>
				</view>
			</view>

			<view class="empty-state" v-else>
				<uni-icons type="empty" size="60" class="empty-icon"></uni-icons>
				<text class="empty-text">未找到玩家数据</text>
				<text class="empty-desc">请先登录或完成用户注册</text>
				<button class="btn-goto-login" @click="navigateToLogin">
					前往登录
				</button>
			</view>
		</view>

		<view class="data-section">
			<text class="section-title">所有存储键值对</text>

			<view class="all-keys-list">
				<view class="key-item" v-for="(value, key) in storageData" :key="key">
					<text class="key-name">{{ key }}</text>
					<text class="key-value">{{ formatValue(value) }}</text>
				</view>
			</view>
		</view>

		<view class="action-buttons">
			<button class="btn-primary" @click="navigateToMine">
				前往"我的"页面
			</button>
			<button class="btn-secondary" @click="navigateToLogin">
				前往登录页面
			</button>
		</view>
	</view>
</template>

<script>
	// 配置后端服务地址，根据实际情况修改
	const BASE_URL = 'http://localhost:8080';
	
	export default {
		data() {
			return {
				// 存储的所有数据
				storageData: {},
				// 用户数据
				userData: {},
				// 最后更新时间
				lastUpdateTime: '',
				// 上传进度
				uploadProgress: 0,
				// 新昵称输入
				newNickname: ''
			};
		},
		computed: {
			// 判断是否有用户数据
			hasUserData() {
				return !!Object.keys(this.userData).length;
			}
		},
		onLoad() {
			// 页面加载时读取存储数据
			this.loadStorageData();
		},
		onShow() {
			// 页面显示时同步昵称到输入框
			if (this.userData.nickname) {
				this.newNickname = this.userData.nickname;
			}
		},
		methods: {
			// 加载存储数据
			loadStorageData() {
				try {
					// 获取所有存储数据
					const keys = uni.getStorageInfoSync().keys;
					const data = {};

					keys.forEach(key => {
						data[key] = uni.getStorageSync(key);
					});

					this.storageData = data;
					// 提取用户数据
					this.userData = data.userData || {};
					// 更新时间
					this.lastUpdateTime = new Date().toLocaleString();
					
					// 同步昵称到输入框
					if (this.userData.nickname) {
						this.newNickname = this.userData.nickname;
					}

					uni.showToast({
						title: '数据加载成功',
						icon: 'success',
						duration: 1000
					});
				} catch (e) {
					console.error('加载存储数据失败:', e);
					uni.showToast({
						title: '数据加载失败',
						icon: 'none',
						duration: 2000
					});
				}
			},

			// 清除存储数据
			clearStorageData() {
				uni.showModal({
					title: '确认清除',
					content: '确定要清除所有本地存储数据吗？这将导致需要重新登录。',
					success: (res) => {
						if (res.confirm) {
							try {
								uni.clearStorageSync();
								this.storageData = {};
								this.userData = {};
								this.newNickname = '';
								this.lastUpdateTime = new Date().toLocaleString();

								uni.showToast({
									title: '所有数据已清除',
									icon: 'success',
									duration: 1500
								});
							} catch (e) {
								console.error('清除存储数据失败:', e);
								uni.showToast({
									title: '清除失败，请重试',
									icon: 'none',
									duration: 2000
								});
							}
						}
					}
				});
			},

			// 格式化显示值
			formatValue(value) {
				if (typeof value === 'object' && value !== null) {
					return JSON.stringify(value, null, 2).substring(0, 100) + (JSON.stringify(value).length > 100 ? '...' :
						'');
				}
				return String(value);
			},

			// 隐藏部分token
			maskToken(token) {
				if (token.length <= 8) return token;
				return token.substring(0, 4) + '****' + token.substring(token.length - 4);
			},

			// 前往我的页面
			navigateToMine() {
				uni.navigateTo({
					url: '/pages/mine/mine'
				});
			},

			// 前往登录页面
			navigateToLogin() {
				uni.navigateTo({
					url: '/pages/login/login'
				});
			},
			
			// 获取完整的头像URL
			getAvatarUrl() {
				// 如果有头像URL，拼接完整路径
				if (this.userData.avatarUrl) {
					// 检查URL是否已经是完整路径
					if (this.userData.avatarUrl.startsWith('http://') || this.userData.avatarUrl.startsWith('https://')) {
						return this.userData.avatarUrl;
					} else {
						return BASE_URL + this.userData.avatarUrl;
					}
				}
				// 默认头像
				return '/static/images/default-avatar.png';
			},
			
			// 选择头像并上传（调用新的资料修改接口）
			chooseAvatar() {
				// 验证是否有openId
				if (!this.userData.openid) {
					uni.showToast({
						title: '请先登录获取用户信息',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				
				// 选择图片
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0];
						this.uploadAvatar(tempFilePath);
					},
					fail: (err) => {
						console.error('选择图片失败:', err);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 上传头像到新的资料接口
			uploadAvatar(tempFilePath) {
				// 显示加载中
				uni.showLoading({
					title: '上传中...'
				});
				
				// 上传文件到新接口：/user/profile
				const uploadTask = uni.uploadFile({
					url: BASE_URL + '/user/profile', 
					filePath: tempFilePath,
					name: 'file',  // 与后端接口参数名一致
					formData: {
						'openId': this.userData.openid,  // 必传参数
						// 只传头像，不传昵称（单独修改头像）
					},
					success: (uploadFileRes) => {
						uni.hideLoading();
						
						try {
							const result = JSON.parse(uploadFileRes.data);
							if (result.success && result.data && result.data.avatarUrl) {
								// 上传成功，更新本地存储的头像URL
								this.userData.avatarUrl = result.data.avatarUrl;
								this.storageData.userData = this.userData;
								uni.setStorageSync('userData', this.userData);
								
								uni.showToast({
									title: '头像更新成功',
									icon: 'success'
								});
							} else {
								uni.showToast({
									title: result.message || '上传失败',
									icon: 'none'
								});
							}
						} catch (e) {
							console.error('解析上传结果失败:', e);
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('上传头像失败:', err);
						uni.showToast({
							title: '上传失败，请重试',
							icon: 'none'
						});
					}
				});
				
				// 监听上传进度
				uploadTask.onProgressUpdate((res) => {
					this.uploadProgress = res.progress;
					// 可以在这里添加进度显示逻辑
				});
			},
			
			// 单独更新昵称
			updateNickname() {
				// 验证是否有openId
				if (!this.userData.openid) {
					uni.showToast({
						title: '请先登录获取用户信息',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				
				// 验证昵称是否为空
				if (!this.newNickname || this.newNickname.trim() === '') {
					uni.showToast({
						title: '昵称不能为空',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				
				// 验证昵称是否与当前相同
				if (this.newNickname.trim() === (this.userData.nickname || '')) {
					uni.showToast({
						title: '昵称未修改',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				
				// 显示加载中
				uni.showLoading({
					title: '保存中...'
				});
				
				// 调用资料修改接口（只传昵称，单独修改昵称）
				uni.request({
					url: BASE_URL + '/user/profile',
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					data: {
						openId: this.userData.openid,  // 必传参数
						nickname: this.newNickname.trim()  // 只传昵称
					},
					success: (res) => {
						uni.hideLoading();
						
						if (res.data && res.data.success) {
							// 更新成功，同步本地数据
							this.userData.nickname = this.newNickname.trim();
							this.storageData.userData = this.userData;
							uni.setStorageSync('userData', this.userData);
							
							uni.showToast({
								title: '昵称更新成功',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: res.data?.message || '保存失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('更新昵称失败:', err);
						uni.showToast({
							title: '网络错误，请重试',
							icon: 'none'
						});
					}
				});
			}
		}
	};
</script>

<style scoped>
	.test-page {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding: 20rpx;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
	}

	.page-header {
		padding: 30rpx 0;
		text-align: center;
		margin-bottom: 20rpx;
	}

	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #2c3e50;
		display: block;
		margin-bottom: 10rpx;
	}

	.page-desc {
		font-size: 26rpx;
		color: #666;
	}

	.storage-info-card {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 25rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.card-title {
		font-size: 30rpx;
		font-weight: 600;
		color: #333;
	}

	.card-actions {
		display: flex;
		gap: 15rpx;
	}

	.btn-refresh {
		background-color: #3498db;
		color: white;
		border: none;
		border-radius: 6rpx;
		padding: 8rpx 15rpx;
		font-size: 24rpx;
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.btn-clear {
		background-color: #e74c3c;
		color: white;
		border: none;
		border-radius: 6rpx;
		padding: 8rpx 15rpx;
		font-size: 24rpx;
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.storage-stats {
		padding-top: 15rpx;
		border-top: 1rpx solid #f0f0f0;
	}

	.stat-item {
		display: flex;
		margin-bottom: 15rpx;
	}

	.stat-label {
		font-size: 26rpx;
		color: #666;
		width: 200rpx;
	}

	.stat-value {
		font-size: 26rpx;
		color: #333;
		flex: 1;
	}

	.data-section {
		margin-bottom: 30rpx;
	}

	.section-title {
		font-size: 28rpx;
		color: #2c3e50;
		margin-bottom: 15rpx;
		display: block;
		font-weight: 600;
	}

	.data-card {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 25rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	/* 头像样式 */
	.avatar-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 30rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}
	
	.avatar-wrapper {
		position: relative;
		width: 160rpx;
		height: 160rpx;
		border-radius: 50%;
		overflow: hidden;
		margin-bottom: 15rpx;
		border: 2rpx solid #eee;
	}
	
	.user-avatar {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}
	
	.avatar-upload-overlay {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 40rpx;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		opacity: 0;
		transition: opacity 0.3s;
	}
	
	.avatar-wrapper:hover .avatar-upload-overlay {
		opacity: 1;
	}
	
	.avatar-hint {
		font-size: 24rpx;
		color: #666;
	}
	
	/* 昵称编辑样式 */
	.nickname-edit {
		display: flex;
		align-items: center;
		padding: 15rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
		margin-bottom: 15rpx;
	}
	
	.nickname-input-group {
		flex: 1;
		display: flex;
		gap: 10rpx;
		align-items: center;
	}
	
	.nickname-input {
		flex: 1;
		height: 60rpx;
		border: 1rpx solid #ddd;
		border-radius: 6rpx;
		padding: 0 15rpx;
		font-size: 26rpx;
	}
	
	.btn-save-nickname {
		background-color: #2ecc71;
		color: white;
		border: none;
		border-radius: 6rpx;
		padding: 8rpx 20rpx;
		font-size: 24rpx;
		white-space: nowrap;
	}

	.data-item {
		display: flex;
		padding: 15rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.data-item:last-child {
		border-bottom: none;
	}

	.data-key {
		font-size: 26rpx;
		color: #666;
		width: 180rpx;
	}

	.data-value {
		font-size: 26rpx;
		color: #333;
		flex: 1;
		word-break: break-all;
	}
	
	.url-value {
		color: #27ae60;
		font-size: 24rpx;
	}

	.token-value {
		color: #3498db;
	}

	.token-preview {
		font-size: 22rpx;
		color: #999;
		margin-left: 10rpx;
	}

	.empty-state {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 60rpx 20rpx;
		text-align: center;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.empty-icon {
		color: #ccc;
		margin-bottom: 20rpx;
	}

	.empty-text {
		font-size: 28rpx;
		color: #666;
		display: block;
		margin-bottom: 10rpx;
	}

	.empty-desc {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 30rpx;
	}
	
	.btn-goto-login {
		background-color: #3498db;
		color: white;
		border: none;
		border-radius: 6rpx;
		padding: 10rpx 30rpx;
		font-size: 26rpx;
	}

	.all-keys-list {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 15rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.key-item {
		padding: 15rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.key-item:last-child {
		border-bottom: none;
	}

	.key-name {
		font-size: 26rpx;
		font-weight: 500;
		color: #2980b9;
		display: block;
		margin-bottom: 5rpx;
	}

	.key-value {
		font-size: 24rpx;
		color: #666;
		word-break: break-all;
		background-color: #f9f9f9;
		padding: 10rpx;
		border-radius: 6rpx;
		display: block;
		font-family: monospace;
	}

	.action-buttons {
		display: flex;
		gap: 20rpx;
		margin-top: 40rpx;
		padding: 0 10rpx;
	}

	.btn-primary {
		flex: 1;
		background-color: #3498db;
		color: white;
		border: none;
		border-radius: 8rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
	}

	.btn-secondary {
		flex: 1;
		background-color: #fff;
		color: #3498db;
		border: 1rpx solid #3498db;
		border-radius: 8rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
	}
</style>
    